package cn.yhbk.web.modules.manager.Service.Impl;

import cn.yhbk.web.common.exception.ApiException;
import cn.yhbk.web.modules.manager.Service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;

@Service
public class EmailServiceImpl implements EmailService {

    private static final String EMAIL_TITLE = "【奖学金管理系统】";
    public static final String MAIL_FROM = "2770063826@qq.com";

    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    @Async
    public void sendNoticeSuccess(String email, String jobNumber, String name) {
        String content = name + "("+ jobNumber + ")的加分绩点已审核完毕，详情请登录奖学金官网查看。";
        sendEmail(EMAIL_TITLE, content, email);
    }

    @Override
    @Async
    public void sendNoticeFail(String email, String jobNumber, String name) {
        String content = name + "("+ jobNumber + ")的加分绩点审核材料有问题，详情请登录奖学金官网查看。";
        sendEmail(EMAIL_TITLE, content, email);
    }

    public void sendEmail(String title, String content, String email) {
        try{
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
            mimeMessageHelper.setFrom(MAIL_FROM);
            mimeMessageHelper.setTo(email);
            mimeMessageHelper.setSubject(title);
            //  true表示支持html格式
            mimeMessageHelper.setText(content, true);
            // 发送邮件
            javaMailSender.send(mimeMessage);
        } catch (Exception e){
            throw new ApiException("发送邮箱出错");
        }
    }
}
